<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import { defineProps } from "vue";
import geoJson from "./china.json";

// 1. 定义父组件传递的 props
const props = defineProps({
  data: {
    type: Array,
    default: () => [
      { value: 1048, name: "脱尾主纱" },
      { value: 735, name: "敬酒礼服" },
      { value: 580, name: "迎宾礼服" },
      { value: 484, name: "晨袍" },
    ],
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 2. 封装初始化图表的函数（复用）
const initChart = async (datas) => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);


  echarts.registerMap("china", geoJson);
  let geoCoordMap = {},
    data = [],
    lineData = [];
  geoJson.features.forEach(function (item, index) {
    let name = item.properties.name,
      cp = item.properties.center;
    if (cp) {
      geoCoordMap[name] = cp; // 地区经纬度
      data.push({
        name: name,
        value: cp.concat(Math.round(Math.random() * 100)),
      });
      if (name != "北京") {
        lineData.push([
          { name: "北京" },
          { name: name, value: Math.round(Math.random() * 100) },
        ]);
      }
    }
  });

  let convertData = function (data) {
    let res = [];
    for (let i = 0; i < data.length; i++) {
      let geoCoord = geoCoordMap[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: geoCoord.concat(data[i].value),
        });
      }
    }
    return res;
  };
  const option = {
    visualMap: {
      show: false,
      min: 0,
      max: 100,
      left: "left",
      top: "bottom",
      text: ["高", "低"], // 文本，默认为数值文本
      calculable: true,
      seriesIndex: [1],
      inRange: {
        color: ["#004693"], // 蓝绿
      },
    },
    legend: {
      show: false,
    },
    geo: {
      show: true,
      map: "china",
      roam: true,
      zoom: 1.25,
      label: {
        normal: {
          show: false,
        },
        emphasis: {
          show: false,
        },
      },
      itemStyle: {
        normal: {
          areaColor: "#031525",
          borderWidth: 1,
          borderColor: "#00CFFC",
        },
        emphasis: {
          areaColor: "#2B91B7",
        },
      },
    },
    series: [
      {
        name: "散点",
        type: "scatter",
        coordinateSystem: "geo",
        data: convertData(data),
        symbolSize: 5,
        // symbolSize: function(val) {
        //     return val[2] / 10;
        // },
        label: {
          normal: {
            formatter: "{b}",
            position: "bottom",
            show: true,
          },
          emphasis: {
            show: true,
          },
        },
        itemStyle: {
          normal: {
            color: "red",
          },
        },
      },
      {
        type: "map",
        map: "china",
        geoIndex: 0,
        roam: true,
        aspectScale: 0.75, //长宽比
        showLegendSymbol: false, // 存在legend时显示
        label: {
          normal: {
            show: true,
          },
          emphasis: {
            show: false,
            textStyle: {
              color: "#fff",
            },
          },
        },
        itemStyle: {
          normal: {
            areaColor: "#031525",
            borderColor: "#3B5077",
          },
          emphasis: {
            areaColor: "#2B91B7",
          },
        },
        animation: false,
        data: data,
      },
      {
        name: "点",
        type: "scatter",
        coordinateSystem: "geo",
        symbol: "pin", //气泡
        symbolSize: function (val) {
          return 40;
        },
        label: {
          show: true,
          formatter: function (parm) {
            return parm.value[4];
          },
          textStyle: {
            color: "#fff",
          },
        },
        itemStyle: {
          color: "#F62157", //标志颜色
        },
        zlevel: 6,
        data: convertData(data),
      },
    ],
  };
  chartInstance.setOption(option);
};

onMounted(() => {
  initChart(); // 组件挂载时初始化

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

watch(
  () => props.data,
  () => initChart()
);
</script>

<style scoped>
.chart-container {
  width: 100%; /* 自适应父容器宽度 */
  height: 100%;
}
</style>
